Expand description
A token bucket ratelimiter for rust which can be used by either a single thread or shared across threads using a mpsc synchronous channel
Goals
- a simple token bucket ratelimiter
- usable in single or multi thread code
Future work
- consider additional types of ratelimiters
Usage
Construct a new Limiter
and call block between actions. For multi-thread
clone the channel sender to pass to the threads, in a separate thread, call
run on the Limiter
in a tight loop.
Examples
Construct Limiter
to do a count-down.
extern crate ratelimit;
use std::time::Duration;
let mut ratelimit = ratelimit::Builder::new()
.capacity(1) //number of tokens the bucket will hold
.quantum(1) //add one token per interval
.interval(Duration::new(1, 0)) //add quantum tokens every 1 second
.build();
// count down to ignition
println!("Count-down....");
for i in -10..0 {
println!("T {}", i);
ratelimit.wait();
}
println!("Ignition!");
Use the Limiter
to ratelimit multi-threaded cases
extern crate ratelimit;
use std::thread;
use std::time::{Duration, Instant};
let mut ratelimit = ratelimit::Builder::new()
.capacity(1) //number of tokens the bucket will hold
.quantum(1) //add one token per interval
.interval(Duration::new(1, 0)) //add quantum tokens every 1 second
.build();
let mut handle = ratelimit.make_handle();
thread::spawn(move || { ratelimit.run() });
// launch threads
let mut threads = Vec::new();
for _ in 0..10 {
let mut handle = handle.clone();
threads.push(thread::spawn(move || {
handle.wait();
println!("current time: {:?}", Instant::now());
}));
}
for thread in threads {
thread.join().unwrap();
}
println!("time's up!");